/*
 * HSM Proxy Project.
 * Copyright (C) 2013 Frank Cornelis.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.model.security;

import java.util.ArrayList;

import javax.ejb.Stateless;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

@Stateless
public class JBossSecurityManagerBean {

	public void flushApplicationCache(String credentialHash) {
		flushCache(ApplicationSecurityDomain.NAME, credentialHash);
	}

	public void flushAdministratorCache(String name) {
		flushCache(AdministratorSecurityDomain.NAME, name);
	}

	public void flushCache(String securityDomain, String name) {
		ArrayList<MBeanServer> mbeanServers = MBeanServerFactory
				.findMBeanServer(null);
		MBeanServer mbeanServer = mbeanServers.get(0);
		ObjectName jaasManager;
		try {
			jaasManager = new ObjectName(
					"jboss.as:subsystem=security,security-domain="
							+ securityDomain);
		} catch (Exception e) {
			throw new SecurityException("no JBoss?");
		}
		Object[] params = { name };
		String[] signature = { "java.lang.String" };
		try {
			mbeanServer.invoke(jaasManager, "flushCache", params, signature);
		} catch (Exception e) {
			throw new SecurityException("could not clear JAAS cache");
		}
	}
}
